<template>
  <page-wrap back hide-tab title="我的订单" stayStill>
    <view class="props-records">
      <u-tabs :current="currentIndex" name="name" :list="categoryList" @change="handleCateClick" height="88"
        :active-item-style="activeItemStyle" :gutter="24" :bar-style="barStyle" font-size="28" :inactive-color="'#999999'"
        bg-color="transparent"></u-tabs>
      <view class="records careerRecords" v-if="currentIndex == 0">
        <view class="record u-flex" v-for="item in careerRecords" :key="item.id" @click="handleCareerRecordsClick(item)">
          <view class="record-middle">
            <view class="record-name row">{{
              item.rightProducts
            }}</view>
            <view class="record-num row">购买数量：<text class="gray">{{
              item.productNum
            }}</text>
            </view>
            <view class="record-order row">订单号：<text class="gray">{{ item.orderNo }}</text></view>
            <view class="record-time">时间：<text class="gray">{{ item.payTime }}</text>
            </view>
          </view>
          <view class="record-right">
            <view class="price">
              <text class="sign">￥</text>{{ item.price }}
            </view>
            <view class="action">

              <view class="invoice">
                <text>去查看</text>
                <u-icon name="arrow-right" class="icon-arrow-right" color="#ccc">
                </u-icon>
              </view>
            </view>
          </view>
        </view>
        <u-loadmore v-if="careerRecords.length" :status="careerStatus" />
        <Empty v-if="!careerRecords.length" :baseImg="emptyImg" text="暂无订单" :fontWeight="400" />
      </view>
      <view class="records" v-if="currentIndex == 1">
        <view class="record u-flex" v-for="item in records" :key="item.id" @click="handleSelect(item)">
          <view class="record-left">
            <text v-if="item.canSelect" class="icon icon-select" :class="{ selected: item.selected }"></text>
          </view>
          <view class="record-middle">
            <view class="record-name row">{{
              item.OrderDisplayName || item.orderItem.productName
            }}</view>
            <view class="record-num row">购买数量：<text class="gray">{{
              item.orderItem.productQuantity
            }}</text>
            </view>
            <view class="record-order row">订单号：<text class="gray">{{ item.orderSn }}</text></view>
            <view class="record-time">时间：<text class="gray">{{ item.payTime }}</text>
            </view>
          </view>
          <view class="record-right">
            <view class="price">
              <text class="sign">￥</text>{{ item.payAmount }}
            </view>
            <view class="action" @click.stop="handleInvoice(item)">
              <view v-if="item.drawState == 30" class="billed">已拒绝</view>
              <view v-else-if="item.drawState == 20" class="billed">已开票</view>
              <view v-else class="invoice">
                <text> {{ item.drawState == 10 ? "申请变更" : "开票" }}</text>
                <u-icon name="arrow-right" class="icon-arrow-right" color="#F75A3E">
                </u-icon>
              </view>
            </view>
          </view>
        </view>
        <u-loadmore v-if="records.length" :status="status" />
        <Empty v-if="!records.length" :baseImg="emptyImg" text="暂无订单" :fontWeight="400" />
      </view>

      <view class="records-action u-flex u-border-top" v-if="currentIndex == 1">
        <view class="select-all u-border-right" @click="handleSelectAll">
          <text class="icon icon-select" :class="{ selected: isAll }"></text>
          <view class="select-text">全选</view>
        </view>
        <view class="select-info">
          {{ selectionLength }}个订单，<text class="price">共{{ totalMoney }}元</text>
        </view>
        <view class="btn btn-primary btn-invoice" :class="{ disable: selectionLength == 0 }" @click="bulkInvoicing">
          批量开票
        </view>
      </view>
    </view>

    <u-popup v-model="showInfo" mode="bottom" closeable @open="onPopupOpen" @close="onPopupClose">
      <view class="info-popup">
        <view class="info-title u-text-center">
          {{ selectedItme.drawState == 10 ? "信息变更" : "信息填写" }}</view>
        <u-form :model="form" ref="uForm" label-width="auto" :border-bottom="false">
          <u-form-item v-for="item in formList" :key="item.prop" :label="item.label" :prop="item.prop"
            :border-bottom="false" @click.capture.native="handleFormItemSelect(item, index)">
            <u-select v-if="item.comp == 'select'" v-model="item.show" :list="item.list"
              @confirm="handleSelectConfirm($event, item)"></u-select>
            <u-input v-model="form[item.propLabel || item.prop]" :type="item.type" :placeholder="item.inputPlaceholder"
              input-align="right" height="24" />
          </u-form-item>
          <u-form-item label="默认" :border-bottom="false">
            <u-switch slot="right" v-model="form.default" size="32" class="u-p-t-16 u-p-b-16"
              active-color="#F75A3E"></u-switch>
          </u-form-item>
        </u-form>
        <view class="btn btn-primary" @click="submit">提交申请</view>
      </view>
    </u-popup>
  </page-wrap>
</template>

<script>
import Empty from "@/components/Empty.vue";

import { checkEmailValid, formatTime } from "@/utils/handle";
import { headerTypeList } from "@/utils/data";
import {
  getOrderList,
  addInvoice,
  getInvoiceById,
  updateInvoice,
} from "@/api/modules/company";
import { myOrderList } from "@/api/modules/career.js";

const INFO_KEY = "invoiceInfo";
export default {
  components: {
    Empty,
  },
  data() {
    var validateEmail = (rule, value, callback) => {
      if (!checkEmailValid(value)) return false;
      return true;
    };
    return {
      activeItemStyle: {
        "font-weight": "600",
        color: "#000000",
        "font-size": "32rpx",
      },
      barStyle: {
        width: "20px",
        height: "8px",
        background:
          "linear-gradient(270deg, rgba(255, 255, 255, 0) 0%, #F75A3E 100%)",
        "border-radius": "4px",
        left: "0",
        bottom: "12rpx",
      },
      categoryList: [{ name: "订单详情" }, { name: "开发票" }],
      currentIndex: 0,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      companyId: uni.getStorageSync("company-id"),
      loginStatus: uni.getStorageSync("login-status") || "person",
      navHeight: getApp().globalData.navHeight,
      records: [],
      careerRecords: [],
      pageparam: {
        page: 1,
        pageSize: 20,
      },
      careerPageparam: {
        page: 1,
        pageSize: 20,
      },
      status: "loadmore",
      careerStatus: "loadmore",
      loadText: {
        loadmore: "加载更多",
        loading: "加载中",
        nomore: "没有更多了",
      },
      emptyImg: this.$imgBaseSelf + "common/empty.png",
      multipleSelection: [],
      selectedItme: null,
      totalMoney: 0,
      showInfo: false,
      form: {
        headerType: "",
        headerTypeLabel: "",
        headerTitle: "",
        taxpayerIdentificationNumber: "",
        bankName: "",
        bankNum: "",
        companyAddress: "",
        companyTel: "",
        invoiceEmail: "",
        default: true,
      },
      isSingle: true,
      formList: [
        {
          label: "抬头类型",
          prop: "headerType",
          propLabel: "headerTypeLabel",
          type: "select",
          comp: "select",
          show: false,
          inputPlaceholder: "请选择抬头类型",
          list: headerTypeList,
        },
        {
          label: "发票抬头",
          prop: "headerTitle",
          inputPlaceholder: "请填写发票抬头",
        },
        {
          label: "税号",
          prop: "taxpayerIdentificationNumber",
          inputPlaceholder: "请输入税号",
        },
        {
          label: "开户银行",
          prop: "bankName",
          inputPlaceholder: "请填写开户银行",
        },
        {
          label: "银行账号",
          prop: "bankNum",
          inputPlaceholder: "请输入银行账号",
          type: "number",
        },
        {
          label: "公司地址",
          prop: "companyAddress",
          inputPlaceholder: "请填写公司地址",
        },
        {
          label: "公司电话",
          prop: "companyTel",
          inputPlaceholder: "请填写公司电话",
          type: "number",
        },
        {
          label: "接收邮箱",
          prop: "invoiceEmail",
          inputPlaceholder: "请填写接收邮箱",
        },
      ],
      rules: {
        headerType: {
          required: true,
          message: "请选择抬头类型",
          trigger: ["change"],
        },
        headerTitle: {
          required: true,
          message: "请输入发票抬头",
          trigger: ["blur"],
        },
        taxpayerIdentificationNumber: {
          required: true,
          message: "请输入税号",
          trigger: ["blur"],
        },
        bankName: {
          required: true,
          message: "请填写开户银行",
          trigger: ["blur"],
        },
        bankNum: {
          required: true,
          message: "请输入银行账号",
          trigger: ["blur"],
        },
        companyAddress: {
          required: true,
          message: "请填写公司地址",
          trigger: ["blur"],
        },
        companyTel: {
          required: true,
          message: "请填写公司电话",
          trigger: ["blur"],
        },
        invoiceEmail: {
          required: true,
          validator: validateEmail,
          message: "请输入正确的邮箱地址",
          trigger: ["blur"],
        },
      },
    };
  },
  computed: {
    canSelectionList() {
      return this.records.filter((item) => item.canSelect);
    },
    selectionLength() {
      return this.multipleSelection.length;
    },
    isAll() {
      return (
        this.selectionLength > 0 &&
        this.selectionLength == this.canSelectionList.length
      );
    },
  },
  onReachBottom() {
    console.log("onReachBottom");

    this.loadMore();
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  mounted() {
    this.getData();
    this.getCareerData();
  },
  methods: {
    handleCareerRecordsClick(item) {
      console.log('item', item);
      uni.navigateTo({
        url:
          `/pagesSub/userCenter/careerPathV2/components/zhituPayFinish?fromWhere=myOrderPage&mallOrderId=` +
          item.mallOrderId + '&orderNo=' + item.orderNo,
      });
    },
    handleCateClick(index) {
      this.currentIndex = index;
      if (this.currentIndex == 0) {
      }
    },
    getData(refresh) {
      if (refresh) {
        this.records = [];
        this.status = "loadmore";
        this.pageparam.page = 1;
      }
      this.status = "loading";
      const params = {
        personId: this.personId,
        pageSize: this.pageparam.pageSize,
        page: this.pageparam.page,
        companyId: this.companyId || 0,
        orderType: this.loginStatus,
      };
      getOrderList(params).then((res) => {
        this.status = "loadmore";
        if (res && res.data) {
          let list = res.data.map((item) => {
            item.canSelect = item.drawState == 0 ? true : false;
            item.selected = false;
            item.orderItem = item.orderItemList[0];
            item.OrderDisplayNameArray = item.orderItemList.map((item) => {
              return item.productName;
            });
            item.OrderDisplayName =
              item.OrderDisplayNameArray &&
              item.OrderDisplayNameArray.join(",");
            console.log("item.OrderDisplayName", item.OrderDisplayName);

            item.payTime =
              (item.paymentTime &&
                formatTime(+item.paymentTime, "yyyy-MM-dd HH:mm:ss")) ||
              "";
            return item;
          });
          this.records.push(...list);
          this.pageparam.page++;
        }
        if (res.pageparam) {
          if (this.pageparam.page > res.pageparam.pages) {
            this.status = "nomore";
          }
        } else {
          this.status = "nomore";
        }
      });
    },
    getCareerData(refresh) {
      if (refresh) {
        this.careerRecords = [];
        this.careerStatus = "loadmore";
        this.careerPageparam.page = 1;
      }
      this.careerStatus = "loading";
      const params = {
        personId: this.personId,
        pageSize: this.careerPageparam.pageSize,
        pageNo: this.careerPageparam.page,
      };
      myOrderList(params).then((res) => {
        this.careerStatus = "loadmore";
        if (res && res.data) {
          let list = res.data;
          this.careerRecords.push(...list);
          this.careerPageparam.page++;
        }
        if (res.pageparam) {
          if (this.careerPageparam.page > res.pageparam.pages) {
            this.careerStatus = "nomore";
          }
        } else {
          this.careerStatus = "nomore";
        }
      });
    },
    loadMore() {
      if (this.currentIndex == 0) {
        if (this.careerStatus == "loading" || this.careerStatus == "nomore")
          return false;
        this.getCareerData();
      } else if (this.currentIndex == 1) {
        if (this.status == "loading" || this.status == "nomore") return false;
        this.getData();
      }
    },
    handleSelect(item) {
      if (item.canSelect) {
        item.selected = !item.selected;
        this.changeSelection();
      }
    },
    changeSelection() {
      let list = [];
      this.totalMoney = 0;
      for (let i = 0; i < this.canSelectionList.length; i++) {
        if (this.canSelectionList[i].selected) {
          list.push(this.canSelectionList[i]);
          let num = parseFloat(this.canSelectionList[i].payAmount);
          this.totalMoney = (this.totalMoney * 100 + num * 100) / 100;
        }
      }
      this.multipleSelection = list;
    },
    handleSelectAll() {
      if (this.isAll) {
        this.canSelectionList.forEach((item) => {
          item.selected = false;
        });
        this.multipleSelection = [];
        this.totalMoney = 0;
      } else {
        this.totalMoney = 0;
        this.canSelectionList.forEach((item) => {
          item.selected = true;
          let num = parseFloat(item.payAmount);
          this.totalMoney = (this.totalMoney * 100 + num * 100) / 100;
        });
        this.multipleSelection = this.canSelectionList;
      }
    },

    // 单个开票
    handleInvoice(item) {
      if (item.drawState == 0 || item.drawState == 10) {
        this.selectedItme = item;
        this.isSingle = true;
        this.showInfo = true;
      }
    },

    // 批量开票
    bulkInvoicing() {
      if (this.multipleSelection.length) {
        this.isSingle = false;
        this.showInfo = true;
      } else {
        uni.showToast({
          title: "您未选择任何订单",
          icon: "none",
        });
      }
    },
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.addInvoice();
        }
      });
    },

    onPopupClose() {
      this.$refs.uForm.resetFields();
      for (let k in this.form) {
        this.form[k] = "";
      }
    },
    onPopupOpen() {
      let info = uni.getStorageSync(INFO_KEY);
      if (this.isSingle) {
        if (this.selectedItme.drawState == 0) {
          info && Object.assign(this.form, info);
        } else {
          uni.showLoading();
          this.getInvoiceInfo(this.selectedItme.invoiceId).then((res) => {
            uni.hideLoading();
            if (res.code == 200) {
              let data = res.data[0];
              this.form = Object.assign(this.form, data);
              this.form.headerType = "" + this.form.headerType;
              let item = headerTypeList.find(
                (ele) => ele.value == data.headerType
              );
              this.form.headerTypeLabel = item.label;
            } else {
              uni.showToast({
                title: res.status_desc || "发票信息获取失败",
                icon: "none",
              });
              this.showInfo = false;
            }
          });
        }
      } else {
        if (info) {
          Object.assign(this.form, info);
        }
      }
    },
    handleFormItemSelect(item, index) {
      if (item.comp) {
        item.show = true;
      }
    },
    handleSelectConfirm(e, item) {
      this.form[item.prop] = e[0].value;
      this.form[item.propLabel] = e[0].label;
    },

    addInvoice() {
      let listStr, invoiceNum;
      const isUpdate = this.isSingle && this.selectedItme.drawState == 10;
      if (this.isSingle) {
        listStr = this.selectedItme.id;
        invoiceNum = this.selectedItme.payAmount;
      } else {
        listStr = this.multipleSelection.map((item) => item.id).join(",");
        invoiceNum = this.totalMoney;
      }
      const params = {
        invoiceType: "20", // 发票类型：10电子发票20纸质发票
        headerType: this.form.headerType,
        headerTitle: this.form.headerTitle,
        taxpayerIdentificationNumber: this.form.taxpayerIdentificationNumber,
        companyAddress: this.form.companyAddress,
        companyTel: this.form.companyTel,
        bankName: this.form.bankName,
        bankNum: this.form.bankNum,
        invoiceEmail: this.form.invoiceEmail,
        userId: this.personId,
        orderIdList: listStr,
        invoiceNum: invoiceNum,
        companyId: this.companyId,
      };

      let addFn = addInvoice;

      if (isUpdate) {
        params.invoiceId = this.form.invoiceId;
        params.defaultStatus = "1";
        addFn = updateInvoice;
      }

      uni.showLoading();

      addFn(params).then((res) => {
        uni.hideLoading();
        let msg = "";
        if (res.code == 200) {
          msg = "申请成功";
          if (isUpdate) msg = "更新成功";
          this.hadnleAddSuccess();
        } else {
          msg = res.status_desc || "申请失败";
          if (isUpdate) msg = "更新失败";
        }
        uni.showToast({
          title: msg,
          icon: "none",
        });
      });
    },

    hadnleAddSuccess() {
      if (this.form.default) {
        uni.setStorageSync(INFO_KEY, this.form);
      } else {
        uni.removeStorageSync(INFO_KEY);
        for (let k in this.form) {
          this.form[k] = "";
        }
      }
      // if(this.isSingle) {
      //   this.selectedItme.drawState = 10;
      //   this.selectedItme.canSelect = false;
      //   this.selectedItme.selected = false;
      // } else {
      //   this.multipleSelection.forEach(item => {
      //     item.drawState = 10;
      //     item.canSelect = false;
      //     item.selected = false;
      //   });
      // }
      this.multipleSelection = [];
      this.getData(true);
      this.changeSelection();
      this.showInfo = false;
    },

    // 获取发票详情
    getInvoiceInfo(invoiceId) {
      const params = {
        invoiceId: invoiceId,
        companyId: this.companyId,
        userId: this.personId,
      };
      return getInvoiceById(params);
    },
  },
};
</script>

<style lang="scss" scoped>
@font-face {
  font-family: "D-DIN-PRO-700-Bold";
  /*定义字体名称*/
  src: url("https://img3.job1001.com/ypMp/elan/images/career/positionDictionary/D-DIN-PRO-700-Bold.ttf");
}

.props-records {
  .action {
    display: flex;
    padding: 12rpx $uni-spacing-col-big;
    justify-content: space-between;
    background-color: #ffffff;
  }
}

.records {
  padding: $uni-spacing-col-big;
}

.record {
  margin-bottom: $uni-spacing-col-big;
  padding: $uni-spacing-col-big;
  font-size: $uni-font-size-sm;
  color: #000000;
  background-color: #fff;
  border-radius: $uni-border-radius-lg;

  .row {
    margin-bottom: $uni-spacing-col-base;
  }

  .gray {
    color: $uni-text-color-666;
  }

  &-left {
    padding-right: 32rpx;
    min-width: 60rpx;
  }

  &-middle {
    flex: 1;
  }

  &-right {
    align-self: stretch;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;

    .sign {
      font-size: 28rpx;
    }

    .price {
      font-size: 48rpx;
      font-family: "D-DIN-PRO-700-Bold";
    }

    .billed {
      color: $uni-text-color-666;
    }
  }

  &-name {
    font-size: 34rpx;
    font-weight: 500;
  }

  .action,
  .price {
    color: $u-type-primary;
  }
}

.careerRecords {
  .action {
    color: #ccc;

    .invoice {
      margin-right: -20rpx;
    }
  }
}

.icon {
  &-select {
    width: 28rpx;
    height: 28rpx;
    background-image: url($img-base + "rights/select.png");
    background-size: 100% 100%;

    &.selected {
      background-image: url($img-base + "rights/selected.png");
    }
  }
}

.records-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1;
  padding: 0 $uni-spacing-col-big;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #fff;

  .select-all {
    flex-shrink: 0;
    padding-top: 13rpx;
    margin-right: $uni-spacing-col-lg;
    padding-right: $uni-spacing-col-lg;
    font-size: $uni-font-size-min;
    text-align: center;
  }

  .select-info {
    flex: 1;
    font-size: $uni-font-size-sm;
    color: $uni-text-color-666;

    .price {
      color: $u-type-primary;
    }
  }

  .icon {
    width: 36rpx;
    height: 36rpx;
    margin-right: 0;
  }

  .btn-invoice {
    width: 200rpx;
    margin-top: 5rpx;
    border-radius: 44rpx;

    &.disable {
      opacity: 0.4;
    }
  }
}

.info-popup {
  padding: $uni-spacing-col-big;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  font-size: $uni-font-size-base;
  color: #000000;

  .info-title {
    font-size: $uni-font-size-lg;
  }

  ::v-deep .u-form {
    .u-form-item {
      padding: 12rpx 0;

      .u-input input {
        font-size: inherit;
      }

      .u-form-item--left__content__label {
        margin-bottom: 0;
      }

      .u-form-item__message {
        margin-top: 0;
        height: 0;
      }
    }
  }

  .btn {
    margin-top: 100rpx;
    border-radius: 44rpx;
  }
}
</style>